
package com.hlkj.pay.app.merchant.ext.impl.easypay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.id.IdUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.EasyPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.access.PictureList;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.EasyPaySignUtil;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.HttpUtils;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.common.constants.BaseConstants;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigDto;
import com.hlkj.pay.dto.merchant.ProviderChannelFeeConfigList;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.util.MerchantUtils;
import com.hlkj.pay.vo.order.req.MerchantChannelSplitReq;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;

/**
 * 汇付 商户进件参数处理
 * 
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
public class EasyPayMerchantParamsHandle extends EasyPayMerchantCommonParamsHandle {

    /**
     * 企业商户进件-新增参数组装
     *
     * @param channelMerchantAccessContext
     * @return
     */
    public static CommonResult<Map<String, String>> merchantApplyParams(ChannelMerchantAccessContext channelMerchantAccessContext, EasyPayConfig easyPayConfig, String apiAsync) throws IOException {
        Map<String, String> bodyMap = new HashMap<>();
        MerchantAccessDto merchantAccessDto = channelMerchantAccessContext.getMerchantAccessDto();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessLicenseDO merchantAccessLicenseDO = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessCardDO merchantAccessCardDO = merchantAccessDto.getMerchantAccessCard();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        MerchantAccessCertInfoDO merchantAccessController = merchantAccessDto.getMerchantAccessController();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();

        // 商户全称，不能有特殊字符，仅可包含汉字、数字、字母 (需与营业执照一致，如遇提示重复，请在后面加数字1、2...，若为小微商户，请命名为 商户 xxx。)
        bodyMap.put("version", "1.0");
//        if (StringUtils.hasText(merchantAccessInfo.getApplyNo())) {
//            bodyMap.put("messageType", "AGENTPATCH");
//            bodyMap.put("merTrace", merchantAccessInfo.getApplyNo());
//            bodyMap.put("operaTrace", IdUtils.getSnowflake().nextIdStr());
//        } else {
            bodyMap.put("messageType", "AGMERAPPLY");
            bodyMap.put("operaTrace", merchantAccessInfo.getRequestId());
//        }
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("backUrl", channelMerchantAccessContext.getAsyncReturnUrl());
        bodyMap.put("isContract", "1");

        //商户信息
        Map<String, String> merchantInfo = new HashMap<>();
        merchantInfo.put("merName", merchantAccessInfo.getName());
        merchantInfo.put("merMode", getMchtMode(merchantAccessInfo.getType(),merchantAccessLicenseDO));
        merchantInfo.put("businName", merchantAccessBusiness.getShortName());
        merchantInfo.put("merType", merchantAccessBusiness.getMcc());
        merchantInfo.put("standardFlag", "0");
        merchantInfo.put("merArea", merchantAccessBusiness.getAreaCode());
        merchantInfo.put("merAddr", merchantAccessBusiness.getAddress());
        merchantInfo.put("businBegtime", "0000");
        merchantInfo.put("businEndtime", "2359");
        merchantInfo.put("employeeNum", "1");
        merchantInfo.put("businForm", "02");
        bodyMap.put("merInfo", JsonUtils.toJsonString(merchantInfo));

        //附加信息
        Map<String, String> plusInfo = new HashMap<>();
        plusInfo.put("merLegal", merchantAccessLegal.getName());
        plusInfo.put("legalType", getOldCerType(merchantAccessLegal.getCertType()));
        plusInfo.put("legalCode", merchantAccessLegal.getCertNo());
        plusInfo.put("legalValidity", converValidityTime(merchantAccessLegal.getCertBeginDate(), merchantAccessLegal.getCertEndDate()));
        plusInfo.put("legalPhone", merchantAccessLegal.getPhone());
        plusInfo.put("linkMan", merchantAccessContact.getName());
        plusInfo.put("linkmanType", getOldCerType(merchantAccessContact.getCertType()));
        plusInfo.put("linkmanCode", merchantAccessContact.getCertNo());
        plusInfo.put("linkmanValidity", converValidityTime(merchantAccessContact.getCertBeginDate(), merchantAccessContact.getCertEndDate()));
        plusInfo.put("linkmanPhone", merchantAccessContact.getPhone());
        bodyMap.put("plusInfo", JsonUtils.toJsonString(plusInfo));

        //营业执照信息
        Map<String, String> licInfoInfo = new HashMap<>();
        if ("0".equals(merchantInfo.get("merMode")) || "1".equals(merchantInfo.get("merMode"))) {
            licInfoInfo.put("merLic", merchantAccessLicenseDO.getLicenseCode());
            licInfoInfo.put("licenseType", licenseType(merchantAccessLicenseDO.getLicenseType()));
            licInfoInfo.put("licValidity", converValidityTime(merchantAccessLicenseDO.getLicenseBeginDate(), merchantAccessLicenseDO.getLicenseEndDate()));
            licInfoInfo.put("licName", merchantAccessLicenseDO.getName());
        }
        if (merchantAccessLicenseDO == null || !StringUtils.hasText(merchantAccessLicenseDO.getBusinessScope())) {
            licInfoInfo.put("businScope", merchantAccessBusiness.getBusinessDesc());
        } else {
            licInfoInfo.put("businScope", merchantAccessLicenseDO.getBusinessScope());
        }
        String capital = "0";
        if (merchantAccessLicenseDO != null && StringUtils.hasText(merchantAccessLicenseDO.getRegisteredCapital())) {
            capital = MerchantUtils.divide(new BigDecimal(merchantAccessLicenseDO.getRegisteredCapital()), new BigDecimal(10000)).toString();
        }
        licInfoInfo.put("capital", capital);
        if (merchantAccessLicenseDO != null && StringUtils.hasText(merchantAccessLicenseDO.getAddress())) {
            licInfoInfo.put("licAddr", merchantAccessLicenseDO.getAddress());
        } else {
            licInfoInfo.put("licAddr", merchantAccessBusiness.getAddress());
        }
        licInfoInfo.put("controlerName", merchantAccessController.getName());
        licInfoInfo.put("controlerLegalCode", merchantAccessController.getCertNo());
        licInfoInfo.put("controlerLegalType", getOldCerType(merchantAccessController.getCertType()));
        licInfoInfo.put("controlerLegalValidity", converValidityTime(merchantAccessController.getCertBeginDate(), merchantAccessController.getCertEndDate()));
        bodyMap.put("licInfo", JsonUtils.toJsonStringNotNull(licInfoInfo));

        //结算信息
        Map<String, String> accInfo = new HashMap<>();
        accInfo.put("bankName", merchantAccessCardDO.getBankName());
        accInfo.put("bankCode", merchantAccessCardDO.getBranchCode());
        accInfo.put("account", merchantAccessCardDO.getCardNo());
        accInfo.put("accName", merchantAccessCardDO.getName());
        accInfo.put("accType", getAccType(merchantAccessCardDO.getType()));
        if ("00".equals(accInfo.get("accType"))) {
            if (Objects.equals(MerchantEnum.CARD_TYPE.PRIVATE_NON_CORPORATE_ACCOUNT.getCode(), merchantAccessCardDO.getType())) {
                accInfo.put("legalType", getOldCerType(merchantAccessCardDO.getCertType()));
                accInfo.put("legalCode", merchantAccessCardDO.getCertNo());
                accInfo.put("accPhone", merchantAccessCardDO.getCardPhone());
            } else if (Objects.equals(MerchantEnum.CARD_TYPE.PRIVATE_CORPORATE_ACCOUNT.getCode(), merchantAccessCardDO.getType())) {
                accInfo.put("legalType", getOldCerType(merchantAccessLegal.getCertType()));
                accInfo.put("legalCode", merchantAccessLegal.getCertNo());
                accInfo.put("accPhone", merchantAccessCardDO.getCardPhone());
            }
        }
        bodyMap.put("accInfo", JsonUtils.toJsonString(accInfo));

        //新增，企业对私必传
        if ("0".equals(merchantInfo.get("merMode")) && "00".equals(accInfo.get("accType"))) {
            Map<String, String> accInfoBak = new HashMap<>();
            accInfoBak.put("bankName", merchantAccessCardDO.getOfficialBankName());
            accInfoBak.put("bankCode", merchantAccessCardDO.getOfficialBranchCode());
            accInfoBak.put("account", merchantAccessCardDO.getOfficialCardNo());
            accInfoBak.put("accName", merchantAccessCardDO.getOfficialName());
            accInfoBak.put("accType", "10");
            bodyMap.put("accInfoBak", JsonUtils.toJsonString(accInfoBak));
        }

        //功能信息
        bodyMap.put("funcInfo", JsonUtils.toJsonString(getSceneFunctionList(channelMerchantAccessContext.getMerchantFeeConfigList(), easyPayConfig)));

        //图片信息
        bodyMap.put("picInfoList", JsonUtils.toJsonString(addProcessFileId(channelMerchantAccessContext, easyPayConfig, merchantInfo.get("merMode"), accInfo.get("accType"))));

        return CommonResult.success(bodyMap);
    }

    /** 创建电子协议 */
    public static CommonResult<Map<String, String>> contractApply(String applyNo, EasyPayConfig easyPayConfig) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("messageType", "CONTRACTAPPLY");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("merTrace", applyNo);
        return CommonResult.success(bodyMap);
    }

    /**商户进件状态查询*/
    public static CommonResult<Map<String, String>> queryApplyStatus(String requestId, EasyPayConfig easyPayConfig) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("messageType", "QUERYAUDMER");
        bodyMap.put("operaTrace", requestId);
        return CommonResult.success(bodyMap);
    }

    /**商户详情信息查询*/
    public static CommonResult<Map<String, String>> queryMerchant(String applyNo, EasyPayConfig easyPayConfig) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("messageType", "QUERYMER");
        bodyMap.put("merTrace", applyNo);
        return CommonResult.success(bodyMap);
    }

    /**支付宝/微信拆分*/
    public static CommonResult<Map<String, String>> easySplit(ChannelMerchantBusinessContext channelMerchantBusinessContext, EasyPayConfig easyPayConfig) {
        MerchantChannelSplitReq merchantChannelSplitReq = channelMerchantBusinessContext.getMerchantChannelSplitReq();
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("backUrl", channelMerchantBusinessContext.getAsyncReturnUrl());
        bodyMap.put("operType", "add");
        bodyMap.put("operaTrace", IdUtils.getSnowflake().nextIdStr());
        bodyMap.put("playType", StringUtils.hasText(merchantChannelSplitReq.getPlayType()) ? merchantChannelSplitReq.getPlayType() : "unionPay");
        bodyMap.put("messageType", "SENDZFBORWX");
        bodyMap.put("merTrace", channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo().getApplyNo());
        MerchantAccessAuthDO merchantAccessAuth=new MerchantAccessAuthDO();
        merchantAccessAuth.setMchId(merchantChannelSplitReq.getChannelNo());
        channelMerchantBusinessContext.setMerchantAccessAuthDO(merchantAccessAuth);
        if ("ALIPAY".equals(merchantChannelSplitReq.getTradeType())) {
            merchantAccessAuth.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
            bodyMap.put("tradeType", "Z");
            if (StringUtils.hasText(merchantChannelSplitReq.getChannelNo())) bodyMap.put("appId", merchantChannelSplitReq.getChannelNo());
            else if (StringUtils.hasText(merchantChannelSplitReq.getAlipayAppid())) bodyMap.put("appId", merchantChannelSplitReq.getAlipayAppid());
            else if (StringUtils.hasText(easyPayConfig.getAlipayId())) bodyMap.put("appId", easyPayConfig.getAlipayId());
        } else if ("WECHAT".equals(merchantChannelSplitReq.getTradeType())) {
            merchantAccessAuth.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
            bodyMap.put("tradeType", "W");
            if (StringUtils.hasText(merchantChannelSplitReq.getChannelNo())) bodyMap.put("pubName", merchantChannelSplitReq.getChannelNo());
            else if (StringUtils.hasText(merchantChannelSplitReq.getWechatPubName())) bodyMap.put("pubName", merchantChannelSplitReq.getWechatPubName());
            else if (StringUtils.hasText(easyPayConfig.getPubName())) bodyMap.put("pubName", easyPayConfig.getPubName());
        }
        return CommonResult.success(bodyMap);
    }

    /**微信初始化配置*/
    public static CommonResult<Map<String, String>> wxConfigInit(EasyPayConfig easyPayConfig, MerchantAccessAuthDO merchantAccessAuth, String appId, String path) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("wechatId", merchantAccessAuth.getSubMchId());
        if (StringUtils.hasText(appId)) {
            bodyMap.put("messageType", "ALTERAPPID");
            bodyMap.put("appId", appId);
        } else if (StringUtils.hasText(path)) {
            bodyMap.put("messageType", "ALTERJSAPIPATH");
            bodyMap.put("jsAPIPath", path);
        }
        return CommonResult.success(bodyMap);
    }

    /**微信配置*/
    public static CommonResult<Map<String, String>> wxConfig(ChannelMerchantBusinessContext channelMerchantBusinessContext, EasyPayConfig easyPayConfig, MerchantAccessAuthDO merchantAccessAuth) {
        MerchantWechatConfigDto merchantWechatConfigDto = channelMerchantBusinessContext.getMerchantWechatConfigDto();
        Map<String, String> map = new HashMap<>();
        map.put("clientCode", easyPayConfig.getOrgCode());
        map.put("wechatId", merchantAccessAuth.getSubMchId());
        map.put("version", "1.0");

        if (StringUtils.hasText(merchantWechatConfigDto.getJsAPIPath())) {
            map.put("messageType", "ALTERJSAPIPATH");
            map.put("jsAPIPath", merchantWechatConfigDto.getJsAPIPath());
        } else {
            map.put("appId", merchantWechatConfigDto.getAppId());
            map.put("messageType", "ALTERAPPID");
        }
        return CommonResult.success(map);
    }

    /**微信配置查询*/
    public static CommonResult<Map<String, String>> wxConfigQuery(EasyPayConfig easyPayConfig, MerchantAccessAuthDO merchantAccessAuth) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("messageType", "QUERYWXCONFIG");
        bodyMap.put("wechatId", merchantAccessAuth.getSubMchId());
        return CommonResult.success(bodyMap);
    }

    /**支付宝认证授权查询*/
    public static CommonResult<Map<String, String>> aliAuthQuery(EasyPayConfig easyPayConfig, MerchantAccessAuthDO merchantAccessAuth) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("messageType", "ALIAUTHQUERY");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());

        Map<String, String> alipayMap = new HashMap<>();
        alipayMap.put("sub_merchant_id", merchantAccessAuth.getSubMchId());
        bodyMap.put("alipayBody", JsonUtils.toJsonString(alipayMap));
        return CommonResult.success(bodyMap);
    }

    /**微信认证授权查询*/
    public static CommonResult<Map<String, String>> wxAuthQuery(EasyPayConfig easyPayConfig, MerchantAccessAuthDO merchantAccessAuth) {
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("version", "1.0");
        bodyMap.put("messageType", "APPLYQUERYSTATE");
        bodyMap.put("clientCode", easyPayConfig.getOrgCode());
        bodyMap.put("sub_mchid", merchantAccessAuth.getSubMchId());
        return CommonResult.success(bodyMap);
    }

    private static List<Map<String, String>> getSceneFunctionList(List<ProviderChannelFeeConfigList> merchantFeeConfigList, EasyPayConfig easyPayConfig) {
        Map<Integer, List<ProviderChannelFeeConfigList>> merchantFeeConfigMap = merchantFeeConfigList.stream()
                .collect(Collectors.groupingBy(merchantFeeConfig -> (merchantFeeConfig.getPayWayDO().getType())));
        List<Map<String, String>> list = new ArrayList<>();
        List<Integer> filter = new ArrayList<>();
        merchantFeeConfigMap.forEach((index, value) -> {
            value.forEach(feeConfig -> {
                PayWayDO payWayDO = feeConfig.getPayWayDO();
//                if (!filter.contains(payWayDO.getType())) {
//                    filter.add(payWayDO.getType());
                    Map<String, String> map = new HashMap<>();
                    switch (PayEnums.PAY_TYPE.fromByCode(payWayDO.getType())) {
                        case WECHAT:
                            map.put("funcId", "3");
                            if (StringUtils.hasText(easyPayConfig.getPubName()))
                                map.put("pubName", easyPayConfig.getPubName());
                            map.put("calcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                            list.add(map);
                            break;
                        case ALIPAY:
                            map.put("funcId", "2");
                            if (StringUtils.hasText(easyPayConfig.getAlipayId()))
                                map.put("appid", easyPayConfig.getAlipayId());
                            map.put("calcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                            list.add(map);
                            break;
                        case UNION_APY:
                            if ("offUnionQr".equals(payWayDO.getCode())) {
                                map.put("funcId", "12");
                                map.put("DStlmType", "1");
                                map.put("DStlmMaxAmt", "20");
                                map.put("DFeeLowLimit", "0");
                                map.put("CFeeLowLimit", "0");
                                map.put("DCalcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                                map.put("CCalcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                                list.add(map);
                            }
                            break;
                        case FUNCTION:
                            if (MerchantEnum.SETTLE_CYCLE.D1.getPayWayCode().equals(payWayDO.getCode())) {
                                map.put("funcId", "10");
                                map.put("calcType", "1");
                                map.put("payDateType", "1");
                                map.put("calcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                                list.add(map);
                            } else if (MerchantEnum.SETTLE_CYCLE.D0.getPayWayCode().equals(payWayDO.getCode())) {
                                map.put("funcId", "25");
                                map.put("tradeType", "0");
                                map.put("DCalcType", "1");
                                map.put("CCalcType", "1");
                                map.put("DCalcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                                map.put("CCalcVal", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
                                list.add(map);
                            }
                            break;
                    }
//                }
            });
        });
        List<Map<String, String>> distinctList = list.stream()
                .collect(Collectors.toMap(
                        map -> map.get("funcId"), // 使用 "id" 作为键
                        map -> map, // 保留整个 Map 作为值
                        (existing, replacement) -> existing)) // 如果有重复的 "id"，保留第一个
                .values()
                .stream()
                .collect(Collectors.toList());
        return distinctList;
    }

    private static String getAccType(Integer typeId) {
        if (typeId == 0) {
            return "10";
        } else  {
            return "00";
        }
    }

    private static String getOldCerType(String type) {
//        1:身份证
//        2:护照
//        3:军官证
//        4:士兵证
//        5:回乡证
//        6:户口本
//        7:外国护照
//        8:其他
//        9:暂住证
//        10:警官证
//        11:文职干部证
//        12:港澳台同胞通行证
//        13:外国人居留证
//        14:台胞证
//        15:港澳台居住证

//        "身份证" :"0"
//        "外国公民护照" :"1"
//        "港澳居民来往内地通行证(回乡证)" :"2"
//        "台湾同胞来往内地通行证(台胞证)" :"6"
//        "军官证" :"5"
//        "警官证" :"7"
//        "士兵证" :"8"
//        "户口簿" :"9"
//        "临时身份证" :"10"
//        "外国人居留证" :"11"
//        "单位证件" :"4"
//        "其他证件" :"3"
        switch (type) {
            case "1":
                return "0";
            case "7":
                return "1";
            case "3":
                return "5";
            case "4":
                return "8";
            case "6":
                return "9";
            case "8":
                return "3";
            case "12":
                return "2";
            case "10":
                return "7";
        }
        return null;
    }

    public static String licenseType(String code) {
        // 营业执照类型：
        // 1：营业执照
        // 2：营业执照(多证合一)
        // 3：事业单位法人证书
        // 4：社会团体法人登记证书
        // 5：民办非企业单位登记证书
        // 6：基金会法人登记证书
        // 7：宗教活动场所登记证
        // 8：其他证书/批文/证明
        // 9：执业许可证/执业证
        // 10：基层群众性自治组织特别法人统一社会信用代码证
        // 11：农村集体经济组织登记证
        // 12：业主委员会备案证明

        //默认：01 ； 营业执照类型 01：统一社会信用码，02：其他证明文件，03：工商注册号 04：事业单位法人证书 05：民办非企业单位登记证书 06：基金会法人登记证书
        switch (code) {
            case "1":
            case "2":
            case "14":
                return "01";
            case "8":
                return "02";
            case "3":
                return "04";
            case "5":
                return "05";
            case "6":
                return "06";
            default:
                return null;
        }
    }

    //商户经营类型（0-企业 1-个体户 2-小微）
    private static String getMchtMode(Integer merchantType, MerchantAccessLicenseDO merchantAccessLicenseDO) {
        if (merchantType == 1) {
            return "2";
        } else if ("5".equals(merchantAccessLicenseDO.getCompanyType())) {
            return "1";
        }
        return "0";
    }

    /**
     * 进件返回参数解析
     *
     * @param resMap
     * @param channelMerchantAccessContext
     */
    public static void merchantApplyParamsParse(JSONObject resMap, ChannelMerchantAccessContext channelMerchantAccessContext) {
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessInfo();
        String retCode = resMap.getStr("retCode");
        String retMsg = resMap.getStr("retMsg");
        if ("0000".equals(retCode)) {
            merchantAccessInfo.setApplyNo(resMap.getStr("merTrace"));
            channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SUBMIT);
            channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
        } else {
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
            if (StringUtils.hasText(retMsg)) {
                channelMerchantAccessContext.setRemark(retMsg);
            } else {
                channelMerchantAccessContext.setRemark("易生进件返回错误信息为空,错误码为:" + retCode);
            }
        }
    }

    /**
     * 新增文件参数转换
     *
     * @param channelMerchantAccessContext
     */
    public static PictureList[] addProcessFileId(ChannelMerchantAccessContext channelMerchantAccessContext, EasyPayConfig easyPayConfig, String mchtMode, String acctType) {
        List<PictureList> pictureLists = new ArrayList<>();
        MerchantAccessLicenseDO merchantAccessLicense = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessLicense();
        MerchantAccessCertInfoDO merchantAccessCert = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessLegal();
        MerchantAccessCardDO merchantAccessCard = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessCard();
        MerchantAccessBusinessDO merchantAccessBusinessDO = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessBusiness();
        boolean test = channelMerchantAccessContext.isTest();

        try {
            // 法人身份证人像面
            CommonResult<String> f01 = fileUpload(easyPayConfig, "01", merchantAccessCert.getCertFrontUrl(), test);
            if (f01.isSuccess()) {
                pictureLists.add(new PictureList(f01.getData(), "01"));
            } else {
                throw new Exception(f01.getMsg());
            }
            // 法人身份证国徽面
            CommonResult<String> f02 = fileUpload(easyPayConfig, "02", merchantAccessCert.getCertBackUrl(), test);
            if (f02.isSuccess()) {
                pictureLists.add(new PictureList(f02.getData(), "02"));
            } else {
                throw new Exception(f02.getMsg());
            }
            if (!"2".equals(mchtMode)) {
                // 营业执照
                CommonResult<String> f05 = fileUpload(easyPayConfig,"05", merchantAccessLicense.getLicenseUrl(), test);
                if (f05.isSuccess()) {
                    pictureLists.add(new PictureList(f05.getData(), "05"));
                } else {
                    throw new Exception(f05.getMsg());
                }
            }
            // 收银台
            CommonResult<String> f06 = fileUpload(easyPayConfig,"06", merchantAccessBusinessDO.getStoreCashierDeskUrl(), test);
            if (f06.isSuccess()) {
                pictureLists.add(new PictureList(f06.getData(), "06"));
            } else {
                throw new Exception(f06.getMsg());
            }
            // 内部环境照
            CommonResult<String> f07 = fileUpload(easyPayConfig,"07", merchantAccessBusinessDO.getStoreIndoorUrl(), test);
            if (f07.isSuccess()) {
                pictureLists.add(new PictureList(f07.getData(), "07"));
            } else {
                throw new Exception(f07.getMsg());
            }
            // 营业场所门头照
            CommonResult<String> f08 = fileUpload(easyPayConfig,"08", merchantAccessBusinessDO.getStoreHeaderUrl(), test);
            if (f08.isSuccess()) {
                pictureLists.add(new PictureList(f08.getData(), "08"));
            } else {
                throw new Exception(f08.getMsg());
            }
            if (StringUtils.hasText(merchantAccessBusinessDO.getStoreHeaderUrl())) {
                // 门牌号
                CommonResult<String> f09 = fileUpload(easyPayConfig,"09", merchantAccessBusinessDO.getStoreHeaderUrl(), test);
                if (f09.isSuccess()) {
                    pictureLists.add(new PictureList(f09.getData(), "09"));
                } else {
                    throw new Exception(f09.getMsg());
                }
            }

            log.info("易生图片上传判断是否对公账户 ==> " + acctType);
            if ("10".equals(acctType)) {
                // 开户许可证
                CommonResult<String> f13 = fileUpload(easyPayConfig,"13", merchantAccessCard.getLicenseUrl(), test);
                if (f13.isSuccess()) {
                    pictureLists.add(new PictureList(f13.getData(), "13"));
                } else {
                    throw new Exception(f13.getMsg());
                }
            } else {
                // 结算卡
                CommonResult<String> f14 = fileUpload(easyPayConfig,"14", merchantAccessCard.getSettleCardFrontUrl(), test);
                if (f14.isSuccess()) {
                    if (StringUtils.hasText(f14.getData()))
                        pictureLists.add(new PictureList(f14.getData(), "14"));
                } else {
                    throw new Exception(f14.getMsg());
                }
                // 授权委托书
                CommonResult<String> f15 = fileUpload(easyPayConfig,"15", merchantAccessCard.getAuthUrl(), test);
                if (f15.isSuccess()) {
                    if (StringUtils.hasText(f15.getData()))
                        pictureLists.add(new PictureList(f15.getData(), "15"));
                } else {
                    throw new Exception(f15.getMsg());
                }

                //账号类型 0：对公账户 1：对私法人账户 2：对私非法人账户
                if (merchantAccessCard.getType() == 2) {
                    CommonResult<String> f18 = fileUpload(easyPayConfig,"18", merchantAccessCard.getCertFrontUrl(), test);
                    if (f18.isSuccess()) {
                        if (StringUtils.hasText(f18.getData()))
                            pictureLists.add(new PictureList(f18.getData(), "18"));
                    } else {
                        throw new Exception(f18.getMsg());
                    }
                    CommonResult<String> f19 = fileUpload(easyPayConfig,"19", merchantAccessCard.getCertBackUrl(), test);
                    if (f19.isSuccess()) {
                        if (StringUtils.hasText(f19.getData()))
                            pictureLists.add(new PictureList(f19.getData(), "19"));
                    } else {
                        throw new Exception(f19.getMsg());
                    }
                } else if (merchantAccessCard.getType() == 1) {

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return pictureLists.toArray(new PictureList[pictureLists.size()]);
    }

    /**
     * 文件上传
     *
     * @param fileUrl
     * @param easyPayConfig
     * @return
     * @throws Exception
     */
    public static CommonResult<String> fileUpload(EasyPayConfig easyPayConfig, String picMode, String fileUrl, boolean test) {
        if (!file(fileUrl)) {
            log.info("文件格式错误 跳过文件上传:fileUrl:{},test:{}", fileUrl, test);
            return CommonResult.success();
        }
        try {
            Map<String, String> bodyMap = new HashMap<>();
            bodyMap.put("version", "1.0");
            bodyMap.put("clientCode", easyPayConfig.getOrgCode());
            bodyMap.put("picMode", picMode);
            bodyMap.put("MAC", EasyPaySignUtil.md5Sign(bodyMap, easyPayConfig.getMd5Key()));

            log.info("易生上传图片请求参数:{}", JsonUtils.toJsonString(bodyMap));
            String response = HttpUtils.uploadPost(uploadPath(test), bodyMap, fileUrl);
            log.info("易生上传图片返回参数:{}", response);

            JSONObject respObj = JsonUtils.parseObj(response);
            if (!"0000".equals(respObj.getStr("retCode"))) {
                return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_FILE_ERROR.getCode(), StringUtils.hasText(respObj.getStr("retMsg")) ? respObj.getStr("retMsg") : "图片上传异常");
            }
            return CommonResult.success(respObj.getStr("fileId"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("签名异常:{}", e.getMessage());
            return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_FILE_ERROR.getCode(), e.getMessage());
        }
    }

    public static boolean file(String fileUrl) {
        if (!StringUtils.hasText(fileUrl)) {
            return false;
        }
        int indexOf = fileUrl.lastIndexOf(StringPool.SLASH);
        if (indexOf < 0) {
            return false;
        }
        String fileType = fileUrl.substring(indexOf);
        if (!fileType.contains(StringPool.DOT)) {
            return false;
        }
        return true;
    }

    private static String converValidityTime(String starTime, String endTime) {
        if (StringUtils.hasText(starTime) && StringUtils.hasText(endTime)) {
            String resTime1 ="2039.01.01";
            LocalDate date = LocalDate.parse(starTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String resTime = date.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));

            if (!BaseConstants.MAX_DATA_STRING.equals(endTime)) {
                LocalDate date1 = LocalDate.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                resTime1 = date1.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
            }
            String[] res = new String[] {resTime, resTime1};
            return JsonUtils.toJsonStr(res);
        } else {
            return null;
        }
    }

}
